﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ELearning.Common.Extensions
{
    public static class ComparerHelper
    {
        /// <summary>
        /// 用委托实现IEqualityComparer<T>接口
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        public class ListComparer<T> : IEqualityComparer<T>
        {
            public Func<T, T, bool> EqualsFunc;
            public Func<T, int> GetHashCodeFunc;

            public ListComparer(Func<T, T, bool> Equals, Func<T, int> GetHashCode)
            {
                this.EqualsFunc = Equals;
                this.GetHashCodeFunc = GetHashCode;
            }

            public ListComparer(Func<T, T, bool> Equals) : this(Equals, t => 0)
            {

            }

            public bool Equals(T x, T y)
            {
                if (this.EqualsFunc != null)
                {
                    return this.EqualsFunc(x, y);
                }
                else
                {
                    return false;
                }
            }

            /// <summary>
            /// 获取目标对象的哈希值,只有返回相同的哈希值才能运行Equals方法
            /// </summary>
            /// <param name="obj">获取哈希值的目标类型对象</param>
            /// <returns>返回哈希值</returns>
            public int GetHashCode(T obj)
            {
                if (this.GetHashCodeFunc != null)
                {
                    return this.GetHashCodeFunc(obj);
                }
                else
                {
                    return 0;
                }
            }
        }
    }
}
